package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.StockSearchResultEvent;
import cn.mumzone.pos.model.GoodsTreeEntity;
import cn.mumzone.pos.model.RepoListGoodsEntity;
import cn.mumzone.pos.model.RepositoryEntity;
import cn.mumzone.pos.presenter.StockCheckSearchPresenter;
import cn.mumzone.pos.presenter.contract.StockCheckSearchContract;
import cn.mumzone.pos.ui.adapter.ADA_StockCheck;
import cn.mumzone.pos.ui.fragment.FRA_StockCheck;
import cn.mumzone.pos.ui.widgets.GoodsClassifyView;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener;

/**
 * Created by JoeLjt on 2019/10/8.
 * Email: lijiateng1219@gmail.com
 * Description:
 * 盘点手动搜索页面
 * 搜索后将结果通过 RxBus 发送回 {@link FRA_StockCheck}
 */
public class ACT_SearchStock extends BaseActivity<StockCheckSearchPresenter> implements StockCheckSearchContract.View {

    public static final String KEY_SELECTED_REPO = "key_selected_repo";

    public static final String KEY_LOCAL_LIST = "key_local_list";

    @BindView(R.id.ll_search_title_bar)
    LinearLayout llSearchTitle;
    @BindView(R.id.tv_good_type)
    TextView tvGoodType;
    @BindView(R.id.iv_clear_input)
    ImageView ivClearInput;
    @BindView(R.id.et_search_goods)
    EditText etSearch;
    @BindView(R.id.rb_search)
    RadioButton rbSearch;

    @BindView(R.id.cb_check_all)
    CheckBox cbCheckAll;

    @BindView(R.id.ll_empty_cart)
    LinearLayout llEmpty;
    @BindView(R.id.refresh_layout)
    RefreshLayout refreshLayout;
    @BindView(R.id.rv_cart_goods)
    LRecyclerView rvCart;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;

    @BindView(R.id.fl_container)
    FrameLayout flContainer;

    @BindView(R.id.tv_select_count)
    TextView tvSelectCount;
    @BindView(R.id.tv_add_stock)
    TextView tvAddStock;

    private AlertDialog mSelectGoodsClassifyDialog;
    private List<GoodsTreeEntity> mSelectedClassifyList = new ArrayList<>();
    private GoodsClassifyView goodsClassifyView;

    private RepositoryEntity mSelectedRepo;

    private LRecyclerViewAdapter mGoodsViewAdapter;
    private ADA_StockCheck mStockAdapter;

    private List<RepoListGoodsEntity> localList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        overridePendingTransition(R.anim.right_in, R.anim.right_out);
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.gravity = Gravity.END;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(params);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setFinishOnTouchOutside(true);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        mSelectedRepo = (RepositoryEntity) extras.getSerializable(KEY_SELECTED_REPO);
        localList = (List<RepoListGoodsEntity>) extras.getSerializable(KEY_LOCAL_LIST);

    }

    @Override
    protected void initEventAndData() {

        initSearchCartRv();
        initSelectGoodsClassifyDialog();

        showSearchResultTitleBar();

        updateStockSearchResultUI(true);

        mPresenter.loadGoodsTreeClassify();

    }

    private void showSearchResultTitleBar() {
        llSearchTitle.setVisibility(View.VISIBLE);
    }

    private void updateStockSearchResultUI(boolean showDefault) {
        llEmpty.setVisibility(showDefault ? View.VISIBLE : View.GONE);
        rvCart.setVisibility(!showDefault ? View.VISIBLE : View.GONE);
        cbCheckAll.setVisibility(!showDefault ? View.VISIBLE : View.GONE);
        cbCheckAll.setChecked(false);
        tvAddStock.setEnabled(mStockAdapter.getSelectedCount() > 0);
    }

    private void initSearchCartRv() {


        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                String keyword = etSearch.getText().toString();
                mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "",
                        formatGoodsClassifyId(), keyword, true);
                rvCart.setNoMore(false);
            }
        });


        rvCart.setLayoutManager(new LinearLayoutManager(mContext));
        mStockAdapter = new ADA_StockCheck(this, false);
        mStockAdapter.setOnItemUncheckedListener(new ADA_StockCheck.OnItemUncheckedListener() {
            @Override
            public void onItemUnchecked() {
                tvSelectCount.setText(String.valueOf(mStockAdapter.getSelectedCount()));
                tvAddStock.setEnabled(mStockAdapter.getSelectedCount() > 0);

                // 如果全部选择后勾选全选按钮，取消某一个时取消选择全选
                for (RepoListGoodsEntity entity : mStockAdapter.getDataList()) {
                    if (!entity.isChecked()) {
                        cbCheckAll.setChecked(false);
                        return;
                    }
                }
                cbCheckAll.setChecked(true);
            }
        });
        mGoodsViewAdapter = new LRecyclerViewAdapter(mStockAdapter);
        rvCart.setAdapter(mGoodsViewAdapter);
        rvCart.setPullRefreshEnabled(false);
        rvCart.setLoadMoreEnabled(true);
        rvCart.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                String keyword = etSearch.getText().toString().trim();
                mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "", formatGoodsClassifyId(),
                        keyword, false);
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE) {
                    if (etSearch.hasFocus()) {
                        PosToast.INSTANCE.makeShortToast(mContext, "扫码时软键盘应处于关闭状态，请重试！");
                        v.setText("");
                        EditTextUtil.hideSoftInput(mContext, etSearch);
                        return true;
                    }
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearch.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
                rbSearch.setEnabled(isInputNotEmpty);
                rbSearch.setChecked(isInputNotEmpty);
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);

                    goodsClassifyView.clearSelect();
                    mSelectedClassifyList.clear();
                    tvGoodType.setText(formatGoodsClassifyName());
                    refreshLayout.autoRefresh();
                }
                return false;
            }
        });

    }

    private String formatGoodsClassifyId() {
        if (ListUtil.isListEmpty(mSelectedClassifyList)) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < mSelectedClassifyList.size(); index++) {
            GoodsTreeEntity goodsTreeEntity = mSelectedClassifyList.get(index);
            if ("".equals(goodsTreeEntity.getValue())) {
                return "";
            }
            builder.append(goodsTreeEntity.getValue());
            if (index < mSelectedClassifyList.size() - 1) {
                builder.append(",");
            }
        }
        return builder.toString();
    }

    private String formatGoodsClassifyName() {
        if (ListUtil.isListEmpty(mSelectedClassifyList)) {
            return "全部";
        }
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < mSelectedClassifyList.size(); index++) {
            GoodsTreeEntity goodsTreeEntity = mSelectedClassifyList.get(index);
            builder.append(goodsTreeEntity.getLabel());
            if (index < mSelectedClassifyList.size() - 1) {
                builder.append(",");
            }
        }
        return builder.toString();
    }

    @Override
    protected int getLayout() {
        return R.layout.act_search_stock;
    }

    @Override
    protected View getTargetView() {
        return llGoods;
    }

    @OnClick({R.id.iv_finish, R.id.tv_good_type, R.id.iv_clear_input, R.id.cb_check_all,
            R.id.rb_search, R.id.tv_add_stock})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_finish:
                finish();
                overridePendingTransition(R.anim.right_in, R.anim.right_out);
                break;
            case R.id.tv_good_type:
                showDialog(mSelectGoodsClassifyDialog);
                break;
            case R.id.iv_clear_input:
                if (!TextUtils.isEmpty(etSearch.getText().toString())) {
                    toggleCloseEmpty();
                    etSearch.setText("");
                    mStockAdapter.clear();
                    updateStockSearchResultUI(true);
                }
                break;
            case R.id.rb_search:
                goodsClassifyView.clearSelect();
                mSelectedClassifyList.clear();
                tvGoodType.setText(formatGoodsClassifyName());
                refreshLayout.autoRefresh();
                break;
            case R.id.cb_check_all:
                // 点击后会先操作 CheckBox，所以状态是同步的而不是取反
                mStockAdapter.updateCheckAllStatus(cbCheckAll.isChecked());
                tvSelectCount.setText(String.valueOf(mStockAdapter.getSelectedCount()));
                tvAddStock.setEnabled(mStockAdapter.getSelectedCount() > 0);
                break;
            case R.id.tv_add_stock:
                if (ListUtil.isListEmpty(mStockAdapter.getSelectedItems())) {
                    PosToast.INSTANCE.makeShortToast(mContext, "请先选择商品！");
                    return;
                }
//                RxBus.getDefault().post(new StockSearchResultEvent(mStockAdapter.getSelectedItems()));
                RxBus.getDefault().post(new StockSearchResultEvent(mStockAdapter.getDataList()));
                finish();
                break;
        }
    }

    private void initSelectGoodsClassifyDialog() {
        mSelectGoodsClassifyDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_select_goods_classify_double)
                .setUseRadiusBg(false)
                .setDialogTitle("选择商品分类")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        goodsClassifyView = mSelectGoodsClassifyDialog.getView(R.id.view_goods_classify);
        mSelectGoodsClassifyDialog.getView(R.id.btn_reset).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodsClassifyView.clearSelect();

            }
        });
        mSelectGoodsClassifyDialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelectedClassifyList = goodsClassifyView.getSelectItem();
                tvGoodType.setText(formatGoodsClassifyName());
                closeDialog(mSelectGoodsClassifyDialog);
                etSearch.setText("");
                refreshLayout.autoRefresh();
            }
        });
        goodsClassifyView.setDoubleCheck(true);

    }

    public static void startAct(Activity activity, RepositoryEntity selectedRepo, List<RepoListGoodsEntity> localList) {
        Intent intent = new Intent(activity, ACT_SearchStock.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_SELECTED_REPO, selectedRepo);
        bundle.putSerializable(KEY_LOCAL_LIST, (Serializable) localList);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    public void showGoodsList(List<RepoListGoodsEntity> goodsEntities, boolean isRefresh) {

        refreshLayout.finishRefresh();
        rvCart.refreshComplete(AppConstants.PAGE_SIZE);
        if (ListUtil.isListEmpty(goodsEntities)) {
            rvCart.setNoMore(true);
        }

        for (RepoListGoodsEntity entity : goodsEntities) {
            entity.setChecked(checkGoodsInLocal(entity));
        }

        mStockAdapter.update(goodsEntities, isRefresh);
        if (isRefresh) {
            rvCart.setAdapter(mGoodsViewAdapter);
        } else {
            mGoodsViewAdapter.notifyDataSetChanged();
        }

        updateStockSearchResultUI(ListUtil.isListEmpty(mStockAdapter.getDataList()));

        if (ListUtil.isListEmpty(mStockAdapter.getDataList())) {
            toggleShowEmpty(true, R.mipmap.ic_bill_empty, "未搜索到商品", "");
        } else {
            toggleShowEmpty(false);
        }

    }

    @Override
    public void showGoodsTreeClassify(List<GoodsTreeEntity> goodsTreeEntities) {
        goodsClassifyView.setData(goodsTreeEntities);
    }

    @Override
    protected void showNetErrorEmpty() {
        refreshLayout.finishRefresh();
        showNetErrorEmpty(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ACT_SearchStock.super.toggleCloseEmpty();
                refreshLayout.autoRefresh();
            }
        });
    }

    @Override
    public void showError(String msg) {
        PosToast.INSTANCE.makeShortToast(mContext, msg);
        updateStockSearchResultUI(false);
        cbCheckAll.setVisibility(View.GONE);
        toggleShowEmpty(true, R.mipmap.ic_bill_empty, "未搜索到商品", "");
        refreshLayout.finishRefresh();
    }

    private boolean checkGoodsInLocal(RepoListGoodsEntity goodsEntity) {
        for (RepoListGoodsEntity localEntity : localList) {
            if (localEntity.getGoodsId().equals(goodsEntity.getGoodsId())) {
                return true;
            }
        }
        return false;
    }
}
